<?php

namespace Common\Lib\Weixin;

use Common\Lib\Weixin;
use Think\Log;

class Callbackapi
{
    public static $token;

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)) {
//            $this->logger("R " . $postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            switch ($RX_TYPE) {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
            }
//            $this->logger("T " . $result);
            echo $result;
        } else {
            echo "";
            exit;
        }
    }

    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event) {
            case "subscribe":
                $this->register_to_system($object);
                $content = "感谢您的关注";
                break;
            case "unsubscribe":
                $this->cancel_from_system($object);
                $content = "";
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }

    public function valid()
    {
        $echostr = $_GET['echostr'];
        if ($echostr) {
            if ($this->checkSignature()) {
                exit($echostr);
            } else {
                exit('error');
            }
        }
    }

    public function checkSignature()
    {
        $token     = C('YTATA_WEIXIN_APPTOKEN');
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce     = $_GET["nonce"];

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($signature == $tmpStr) {
            return true;
        } else {
            return false;
        }
    }




    /**
     * 从系统中删除用户
     */
    protected function cancel_from_system($object)
    {
        $openid = addslashes($object->FromUserName);

        $data['is_follow'] = '0';
        $data['unfollowtime'] = time();
        M('Fans')->where(array('openid'=>$openid))->save($data);
    }

    /**
     * 预注册到系统中
     */
    protected function register_to_system($object)
    {
        $openid    = addslashes($object->FromUserName);
        $fans = M('Fans')->where(array('openid'=>$openid))->find();
        if (!empty($fans)) {
            $data['is_follow'] = '1';
            M('Fans')->where(array('openid'=>$openid))->save($data);
        } else {
            $data['openid'] = $openid;
            $userinfo = Weixin::getUserInfo($openid);
            $data['nickname'] = $userinfo['nickname'];
            $data['headimgurl'] = $userinfo['headimgurl'];
            $data['sex'] = $userinfo['sex'];
            $data['city'] = $userinfo['city'];
            $data['country'] = $userinfo['country'];
            $data['province'] = $userinfo['province'];
            $data['is_follow'] = '1';
            $data['followtime'] = time();
            M('Fans')->add($data);
        }
    }

    //接收文本消息
    private function receiveText($object)
    {
        $keyword = trim($object->Content);

    }


    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result  = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    private function transmitNews($object, $arr_item)
    {
        if (!is_array($arr_item)) return;

        $itemTpl  = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($arr_item as $item) $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);

        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item));
        return $result;
    }

    private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <MusicUrl><![CDATA[%s]]></MusicUrl>
    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";


        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

//    private function logger($log_content)
//    {
//        if (isset($_SERVER['HTTP_APPNAME'])) {   //SAE
//            sae_set_display_errors(false);
//            sae_debug($log_content);
//            sae_set_display_errors(true);
//        } else if ($_SERVER['REMOTE_ADDR'] != "127.0.0.1") { //LOCAL
//            $max_size     = 10000;
//            $log_filename = "log.xml";
//            if (file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)) {
//                unlink($log_filename);
//            }
//            file_put_contents($log_filename, date('H:i:s') . " " . $log_content . "\r\n", FILE_APPEND);
//        }
//    }
}